;
var helper = require("../../javascript/helper");
var request = require("request");
var db = require("../../javascript/mysql");
var mysql = new db.mysqlClient("accident");
var spider = function () {
    var that = this;
    this.name = "境内商务出行保险";
    //生成产品数据
    this.genProductInfo = function () {
        let days = [];
        let projects = [];
        for (i = 1; i < 183; i++) {
            days.push(i.toString() + "d");

        };
        // 生成对应时间
        dates = that.handleDate(days);
        plan = {
            planA: {
                "year": ["16-70"],
                "days": days,
                "people_count": ["1"],
                "accident_medical": ["50000"],
                "luggage": [""],
                "exigency_back": ["100000"],
                "relate_mourn": [""],
                "accident_death": ["100000"],
                "death_back": ["50000"]
            },
            planB: {
                "year": ["16-70"],
                "days": days,
                "people_count": ["1"],
                "accident_medical": ["100000"],
                "luggage": [""],
                "exigency_back": ["300000"],
                "relate_mourn": [""],
                "accident_death": ["300000"],
                "death_back": ["80000"]

            },
            planC: {
                "year": ["16-70"],
                "days": days,
                "people_count": ["1"],
                "accident_medical": ["300000"],
                "luggage": ["10000"],
                "exigency_back": ["500000"],
                "relate_mourn": ["7500"],
                "accident_death": ["300000"],
                "death_back": ["100000"]
            }
        }
        for (k in plan) {
            data = helper.product([
                plan[k]["year"], plan[k]["days"], plan[k]["people_count"], plan[k]["accident_medical"], plan[k]["luggage"], plan[k]["exigency_back"], plan[k]["relate_mourn"], plan[k]["accident_death"], plan[k]["death_back"]
            ])
            for (i = 0; i < data.length; i++) {
                dt = helper.formatProductInfo(data[i], plan[k]);
                dt.days = dates[i]
                projects.push(dt);

            }
        }
        return projects;
    }
    //爬虫
    this.httpRequest = function ( dt ) {
        if( dt.accident_medical == "50000"){
            planCd = "1510916987155"
        }else if ( dt.accident_medical == "100000"){
            planCd = "1510916987158"
        }else{
            planCd = "1510916987161"
        }
        params = {
            "startdate": "2020/05/29",
            "enddate": JSON.parse(dt.days).date,
            "items": planCd,
            "peoplecount": "1",
            "planextendvalue": "",
            "productcode": "EAG_T",
        }
        return new Promise(function (resolve, reject) {
            request({
                url: "http://www.epicc.com.cn/eproduct/conproposal/calculate.do",
                method: "POST",
                json: false,
                rejectUnauthorized: false,
                headers: {
                    "Accept": "application/json, text/plain, */*",
                    "Accept-Language": "zh-CN,zh;q=0.9",
                    "Connection": "keep-alive",
                    "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
                    "Cookie": "epicc_tid=epicc.1578282117557422; _gscu_321070471=7828211745c42110; s_fid=51BB77C19E20D92E-16021A351FFE693E; vid=ef0bea9d6c25528ee3c6714b85e0baef; epicc_ntid=AAAAAV6CpgMv3h/HwX4WAg==; svid=0C46E643B8EB2B5549E7AA5CA65A65FB; ag_fid=PqyKLr1Kk08UPYuF; ag_fid=PqyKLr1Kk08UPYuF; udmp_cm_sign_321070471=1; s_vnum=1621564729064%26vn%3D17; s_invisit=true; xY6qiPJDsR=MDAwM2IyNTRmNDgwMDAwMDAwMjUwU1RPECgxNTkwNjI5MDUx; epiccnewEbsWeb=wftY4UF_hQGe0NYA-uE8oZG3o-2QN3FV8zYSayz-PS851bsRsnME!-408920442; epiccnewEbsWebeproduct=SRdY2yaBMBt9uiKKDEHwIIXCEhK0DYtkp4qINf1UrZECfU6Zi4Z4!-1799868909; YXeuzFnfi6=MDAwM2IyNTRmNDgwMDAwMDAwNzYwTUIIMg8xNTkwNjI5MDUy; personalCenter=2ixY4UQgyp5OQtAEzbVsELO5YSjYV_LDq5jAOhFVGl6SXY5UT8kp!-242855368; _gscbrs_321070471=1; _gscs_321070471=90628161cgo1hq11|pv:2; s_getNewRepeat=1590629057761-Repeat; s_cc=true; trkHmClickCoords=977%2C397%2C3652%2Chttp%3A%2F%2Fwww.epicc.com.cn%2Flvyoubaoxian%2Fguoneishangwuchuxingbaoxian%2F%23%2Fmain; R4XlxlrGUk=MDAwM2IyNTRmNDgwMDAwMDAwNWUwahEOTi4xNTkwNjI5ODEy",
                    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.113 Safari/537.36"
                },
                body: helper.urlencode(params)
            },function( err,res,body){
                if(!err && res.statusCode==200){
                    if( body.indexOf("premium") != -1 ){
                        price = JSON.parse( body )[3].premium.toFixed(2).toString();
                        rs = {
                            name:that.name,
                            company:"中国人民保险",
                            price:price
                        }
                        resolve( rs );
                    }
                }
            })


        })
    }
    //时间戳转换天数
    this.handleDate = function (days) {
        let index = 86400;
        let dates = [];
        for (j = 0; j < days.length; j++) {
            var timestamp = parseInt(new Date().getTime() / 1000) + index;
            var date = new Date(parseInt(timestamp) * 1000);
            var year = date.getFullYear();
            var mon = date.getMonth() + 1;
            var day = date.getDate();
            if (mon < 10) {
                month = "0" + mon;
            } else {
                month = mon;
            }
            if (day < 10) {
                dayse = "0" + day;
            } else {
                dayse = day;
            }
            ret = {
                "day": days[j],
                "date": (year + '/' + month + '/' + dayse)
            }
            dates.push(JSON.stringify(ret));
            index += 86400
        }
        return dates;
    }
    //执行爬虫
    this.main = async function(){
        let filters = [];
        data = that.genProductInfo();
        for(i=0;i<data.length;i++){
            dt = data[i];
            rs = await that.httpRequest( dt );
            let price = rs.price;
            if( !filters.includes( price )){
                filters.push( price );
                result = Object.assign( dt,rs );
                
                result.days = JSON.parse( result.days)["day"]
                mysql.insertData( result );
            }
           
        }
        mysql.close();
    }

}